import { Component, ChangeDetectionStrategy, OnDestroy, OnInit, ChangeDetectorRef, Input, NgZone } from '@angular/core';
import { _HttpClient } from '@delon/theme';
import { Subscription } from 'rxjs';
import { ProductViewComponent } from '../../product-view/product-view.component';

/**
 * 感兴趣列表
 */
@Component({
  selector: 'product-interest',
  templateUrl: './product-interest.component.html',
  styleUrls: ['./product-interest.component.less'],
  host: {},
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ProductInterestComponent implements OnInit, OnDestroy {
  styleName = null;
  productCd = null;
  loading = false;
  interests = [];
  private ref$: Subscription;

  constructor(
    private p: ProductViewComponent,
    private ngZone: NgZone,
    public http: _HttpClient,
    private cdr: ChangeDetectorRef,
  ) {}

  ngOnInit(): void {
    this.ref$ = this.p.$refresh.subscribe(vo => {
      this.styleName = vo.product.style;
      this.productCd = vo.product.productCd;
      this.getInterest(this.styleName);
    });
  }

  ngOnDestroy(): void {
    this.ref$.unsubscribe();
  }

  /**
   * 获取感兴趣列表
   */
  getInterest(styleName) {
    this.ngZone.run(() => {
      this.interests = [];
      this.loading = true;
    });

    this.http.get(`/cf/prod/sys-prod/styles/${styleName}`).subscribe(res => {
      this.ngZone.run(() => {
        this.loading = false;
        if (res.status === 200) {
          this.interests = res.data.filter(r => r.productCd !== this.productCd);
          this.interests.forEach(r => {
            if (r.pic) {
              r.pic = `${window.location.origin + window.location.pathname}/cf/admin/sysfile/f/${r.pic}`;
            }
          });
          this.cdr.detectChanges();
        }
      });
    });
  }
}
